package NETWORK;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-15
 * Time: 14:44
 */
public class TcpClient {

    //socket用于客户端/服务器
    Socket socket = null;

    public TcpClient() throws IOException {
        //与服务器建立连接==>指定IP地址(环回)127.0.0.1  端口号: 8000
        socket = new Socket("127.0.0.1",8000);
    }
    public void start() throws IOException {
        System.out.println("与服务器连接成功!!!");
        //用户输入信息==>一个连接,多次响应
        Scanner scanner = new Scanner(System.in);
     //   System.out.print(">");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scannerNet = new Scanner(inputStream);//接收数据
            while(true){
                PrintWriter printWriter =new PrintWriter(outputStream);
                //客户端输入请求
                System.out.print(">");
                String request = scanner.next();
                //将请求发送给客户端
                printWriter.println(request);
                printWriter.flush();//刷新缓冲区,防止发送不过去
                //服务端做出响应后返回给客户端==>此时客户端接收
                String response = scannerNet.next();
                System.out.printf("req = %s ; rep %s\n",request,response);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        TcpClient tcpClient = new TcpClient();
        tcpClient.start();
    }

}
